package com.example.questionnaire.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.questionnaire.common.ResponseCode;
import com.example.questionnaire.dao.*;
import com.example.questionnaire.exception.RException;
import com.example.questionnaire.pojo.DO.*;
import com.example.questionnaire.service.QuestionnairePageService;
import com.example.questionnaire.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class QuestionnairePageServiceImpl implements QuestionnairePageService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private AllQuestionMapper allQuestionMapper;

    @Autowired
    private DoubleChoiceQuestionMapper doubleChoiceQuestionMapper;

    @Autowired
    private FillInQuestionMapper fillInQuestionMapper;

    @Autowired
    private MultipleChoiceQuestionMapper multipleChoiceQuestionMapper;

    @Autowired
    private OptionsMapper optionsMapper;

    @Autowired
    private QuestionnaireViewMapper questionnaireViewMapper;

    @Autowired
    private QuestionnaireDataMapper questionnaireDataMapper;


    private StringBuilder formId = new StringBuilder();
    @Override
    public Map<String, Object> calcQuestionnaireName(String token, String questionnaireName, String questionnaireDescription) {
        StringBuilder middleFormIdTemp = new StringBuilder();
        StringBuilder middleFormId =(CommonUtil.getRandomId());// 生成formId
        //int Fid = Integer.parseInt(middleFormId.toString());
        if(!"".equals(userMapper.selectQuestionnaireToken(token)) && userMapper.selectQuestionnaireToken(token) != null){ // 如果不是第一个formId,则为",formId",反之则为"formId"
            formId = middleFormIdTemp.append(userMapper.selectQuestionnaireToken(token)).append(",").append(middleFormId);
        }
        else {
            formId = middleFormId;
        }
        int Status = 0;// 生成发布状态 仅用于初始化
        StringBuilder status = new StringBuilder();
        //StringBuilder middleStatus = new StringBuilder();
        StringBuilder middleStatusTemp = new StringBuilder();
        if(userMapper.selectQuestionnaireToken(token) != null) {
            status = middleStatusTemp.append(userMapper.selectStatus(token)).append(",").append(Status);
        }
        else {
            status.append(Status);
        }
        int AnswerNumber = 0;// 生成回答问卷的数量 仅用于初始化
        StringBuilder answerNumber = new StringBuilder();
        StringBuilder middleAnswerNumberTemp = new StringBuilder();
        if(userMapper.selectQuestionnaireToken(token) != null) {
            answerNumber = middleAnswerNumberTemp.append(userMapper.selectAnswerNumber(token)).append(",").append(AnswerNumber);
        }
        else {
            answerNumber.append(AnswerNumber);
        }
        Questionnaire questionnaire = new Questionnaire(middleFormId.toString(), questionnaireName, questionnaireDescription,AnswerNumber, Status);

        QuestionnaireView questionnaireView = new QuestionnaireView(middleFormId.toString());
        int k = questionnaireViewMapper.insert(questionnaireView);
        int i = questionnaireMapper.insert(questionnaire);
        if (i+k < 2) {
            throw new RuntimeException("插入失败");
        }
        // 对于user表 当第一次添加时表内无此openId，应该为插入 后面则为更新
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("token", token));
        if (user != null) {
            // 创建一个UpdateWrapper对象
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            // 设置更新条件
            updateWrapper.eq("token", token);
            // 设置需要更新的字段和值
            updateWrapper.set("formid", formId.toString());
            updateWrapper.set("status",status.toString());
            updateWrapper.set("answer_number",answerNumber.toString());
            // 调用更新方法
            userMapper.update(null, updateWrapper);
        } else {
            User temp = new User(token, formId.toString(),status.toString(), answerNumber.toString());
            temp.setToken(token);
            temp.setFormid(formId.toString());
            temp.setStatus(status.toString());
            temp.setAnswerNumber(answerNumber.toString());
            if (userMapper.insert(temp) < 1) {
                throw new RuntimeException("插入失败");
            }
        }
        // 生成返回对象
        Map<String,Object> temp = new HashMap<>();
        temp.put("formId",middleFormId.toString());
        temp.put("questionnaireNames", questionnaireName);
        temp.put("questionnaireDescription", questionnaireDescription);
        temp.put("status", Status);
        temp.put("answerNumber",AnswerNumber);
        return temp;
    }
    @Override
    public boolean updateAddQuestionnaireDescription(String formid, String questionnaireNames, String questionnaireDescription) throws RException {
// 创建一个UpdateWrapper对象
        UpdateWrapper<Questionnaire> updateWrapper = new UpdateWrapper<>();

// 设置更新条件
        updateWrapper.eq("formid", formid);

// 设置需要更新的字段和值
        updateWrapper.set("questionnaire_names", questionnaireNames);

        updateWrapper.set("questionnaire_description", questionnaireDescription);


// 调用更新方法
        int i = questionnaireMapper.update(null, updateWrapper);
        if (i < 1){
            throw new RException(ResponseCode.ERROR.getDesc(), ResponseCode.ERROR.getCode());
        }
        return true;

//        boolean updateResult = questionnaireMapper.update(null, updateWrapper) > 0;
//        if (updateResult) {
//            System.out.println("Questionnaire updated successfully.");
//        } else {
//            System.out.println("Failed to update questionnaire.");
//        }
//
//        return updateResult;
    }
    @Override
    @Transactional
    public List<Map<String, Object>> getQuestionnaireNames(String token) throws RException {
        User user = new User();
        user = userMapper.selectOne(new QueryWrapper<User>().eq("formid", userMapper.selectQuestionnaireToken(token)));
        List<Map<String, Object>> temp = new ArrayList<>();
        if (user != null) {
            String[] FIds = userMapper.selectQuestionnaireToken(token).split(",");
            //System.out.println(userMapper.selectQuestionnaireId(openId));
            for (String formId : FIds) {

                Map<String,Object> tempMap = new HashMap<>();
                tempMap.put("formId",formId);
                tempMap.put("questionnaireNames", questionnaireMapper.selectQuestionnaireName(formId));
                tempMap.put("questionnaireDescription", questionnaireMapper.searchAllByQuestionnaireDescriptionIn(formId));
                tempMap.put("status", questionnaireMapper.selectStatus(formId));
                tempMap.put("answerNumber",questionnaireDataMapper.selectAnswerNumber(formId));
                temp.add(tempMap);
            }
        }
        System.out.println(temp);
        return temp;
    }



    @Override
    public boolean deleteQuestionnaire(String formid, String token) {
        QueryWrapper<AllQuestion> wrapper = new QueryWrapper<>();
        wrapper.eq("formid",formid);
        wrapper.select("subject_id");
        List<AllQuestion> allQuestion = allQuestionMapper.selectList(wrapper);
        if(allQuestion != null){
            for (AllQuestion subjectId : allQuestion) {
                QueryWrapper<Options> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("subject_id",subjectId.getSubjectId());
                int i = optionsMapper.delete(wrapper1);
                QueryWrapper<DoubleChoiceQuestion> wrapper2 = new QueryWrapper<>();
                wrapper2.eq("subject_id",subjectId.getSubjectId());
                int j = doubleChoiceQuestionMapper.delete(wrapper2);
                QueryWrapper<MultipleChoiceQuestion> wrapper3 = new QueryWrapper<>();
                wrapper3.eq("subject_id",subjectId.getSubjectId());
                int k = multipleChoiceQuestionMapper.delete(wrapper3);
                QueryWrapper<FillInQuestion> wrapper4 = new QueryWrapper<>();
                wrapper4.eq("subject_id",subjectId.getSubjectId());
                int l = fillInQuestionMapper.delete(wrapper4);
                if (i+j+k+l < 0){
                    throw new RuntimeException("删除失败");
                }
            }
        }
        int allQuestion1 = allQuestionMapper.delete(wrapper);
        if (allQuestion1 < 0 ){
            throw new RuntimeException("删除失败");
        }

        QueryWrapper<Questionnaire> wrapper5 = new QueryWrapper<>();
        wrapper5.eq("formid",formid);
        int i = questionnaireMapper.delete(wrapper5);
        if (i < 0 ){
            throw new RuntimeException("删除失败");
        }


        String str = userMapper.selectQuestionnaireToken(token); //原字符串
        String newStr="";  //新字符串
        String[] array=str.split(",");  //字符串转数组
        List<String> list= Arrays.asList(array);
        List<String> arrList = new ArrayList<String>(list);  //字符串转集合
        arrList.remove(formid);  //要删除的元素

        String[] strings = new String[arrList.size()];  //再将集合转为数组
        String[] newArray = arrList.toArray(strings);

        //遍历数组，插入逗号
        for(int j=0;j<newArray.length;j++){
            newStr+=newArray[j]+",";
        }
        if(!"".equals(newStr)){   //如果删完之后字符串不为空
            newStr=newStr.substring(0, newStr.length()-1);  //删除最后的逗号
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("token", token)
                .set("formid", newStr);

        int K = userMapper.update(null, updateWrapper);
        if (K < 1) {
            throw new RuntimeException("插入失败");
        }

        return true;
    }

    @Override
    public boolean QuestionnaireRelease(String formid, String status) {
        UpdateWrapper<Questionnaire> wrapper = new UpdateWrapper<>();
        wrapper.eq("formid", formid)
                .set("status", status);
        if(questionnaireMapper.update(null, wrapper) < 1){
            throw new RuntimeException("设置失败");
        }
        return true;
    }

    @Override
    public String getQuestionnaireName(String formid) {

        return questionnaireMapper.selectQuestionnaireName(formid);
    }

    @Override
    public Integer GetQuestionnaireStatus(String formid) {

//        Map<String,Integer> map =new HashMap<>();
//        map.put("status",questionnaireMapper.selectStatus(formid));
        return questionnaireMapper.selectStatus(formid);
    }


}
